<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\adminapi\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use app\service\log\LogService;

class AdminLogMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        $response = $handler($request);
        if (!isset($request->user)) {
            return $response;
        }
        $user = $request->user;
        $action     = $request->action;
        $controller = $request->controller;
        $reflection = new \ReflectionMethod($controller, $action);
        $docComment = $reflection->getDocComment();
        $content    = '';

        // Get content after @notes in comments
        if (preg_match('/@notes(.*?)\n/', $docComment, $matches)) {
            $content .= $matches[1];

            // Get response result msg
            $exception = $response->exception();
            if ($exception && isset($exception->respone)) {
                $result  = $exception->respone;
                $content .= ' ： ' . $result['msg'];
            }

            // Request information
            $params = $request->all();
            $params = array_filter($params, function ($value) {
                if (is_array($value)) {
                    return !empty($value);
                } else {
                    return !is_null($value);
                }
            });
            $params = empty($params) ? null : json_encode($params, JSON_UNESCAPED_UNICODE);

            try {
                (new LogService())->sence('admin')->write($user, $params, $request->path(), $content);
            } catch (\Exception $e) {
            }
        }

        return $response;
    }
}
